import { ProvideInfo } from './../../../../../scripts/managers/SDK/IapSDKManager';
import { udm } from './../../../../../scripts/managers/UserDataManager';
import { _decorator, Node, find, Button } from 'cc';
import { BaseView } from '../../../../../scripts/libs/rxjs/cc3/BaseView';
import { IapProductInfo } from '../../../../../scripts/managers/SDK/IapSDKManager';
import { DevConfig } from '../../../../../scripts/managers/DevConfig';
import { Label } from 'cc';
import { IapButtonItem } from '../../ShopPanel/IapButtonItem';
import { instantiate } from 'cc';
import { BundleItem } from './BundleItem';
import { CoinItem } from './CoinItem';
import { BindButton } from '../../../../../scripts/libs/rxjs/cc3/BindButton';
import { IntervalStartNow } from '../../../../../scripts/libs/rxjs/cc3/CreatorSchedule';
import { timem } from '../../../../../scripts/managers/TimeManager';
import { Sprite } from 'cc';
import { thinking_sdk_m } from '../../../../../scripts/managers/SDK/ThinkingCocosSDKManager';
import { gm } from '../../../../../scripts/managers/GameManager';
import { adsm } from '../../../../../scripts/managers/AdsManager';
import { MSResolve, MSRToString_th_m } from '../../../../../scripts/libs/utils/date';
import { color } from 'cc';
import { ScrollView } from 'cc';
import { optimizeScrollView } from '../../../../../scripts/libs/utils/ScrollView/OptimizeScrollView';
import { GotAwardPanel } from '../../GotAwardPanel/GotAwardPanel';
import { nc } from '../../../../../scripts/libs/rxjs/NotificationCenter';
import { Vec2 } from 'cc';
import { v2 } from 'cc';
import { v3 } from 'cc';
import { Vec3 } from 'cc';
import { lm } from '../../../LobbyManager';
import { Layout } from 'cc';
import { UITransform } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('ShopPage')
export class ShopPage extends BaseView {


    @property(Node)
    viewNode: Node = null;

    @property(Node)
    contentNode: Node = null;

    @property(Node)
    topNode: Node = null;

    @property(ScrollView)
    scrollView: ScrollView = null;

    @property(Node)
    noAds0ItemNode: Node = null;

    @property(Node)
    noAds1ItemNode: Node = null;

    @property(Node)
    bundleItemPrefabNode: Node = null;

    @property(Node)
    starterContainer: Node = null;

    @property(Node)
    bundleContainer: Node = null;

    @property(Node)
    coinItemPrefabNode: Node = null;

    @property(Node)
    coinContainer: Node = null;

    @property(Node)
    freeCoinItemNode: Node = null;

    @property(Button)
    freeAdsButton: Button = null;

    @property(Node)
    freeAdIcon: Node = null;

    @property(Node)
    groupNoAdsNode: Node = null;

    @property(Node)
    groupStarterNode: Node = null;

    _autoScrollToTop = false;

    willBind(): void {

        this.bundleItemPrefabNode.removeFromParent();
        this.coinItemPrefabNode.removeFromParent();

        optimizeScrollView(this.scrollView);

        this.adaptive();
    }

    _pageTouchStart: Vec2 = null;
    _pageTouchDiff: Vec2 = v2();
    _pageScrollType: string = null; // 页面滑动模式

    useObserves() {
        return [
            BindButton(this.freeAdsButton).subscribe(this.freeAdsButtonClicked.bind(this)),
            udm.iapStat.subscribe(this.refresh.bind(this)),
            udm.freeAdsStat.subscribe(this.refreshFreeAds.bind(this)),
            IntervalStartNow(1, this.node).subscribe(this.refreshFreeAds.bind(this)),
            udm.noAds.subscribe(this.noAdsChanged.bind(this)),
            // BindNodeTouch(this.scrollView.node).subscribe(_ => {
            //     switch (_.type) {
            //         case 'touch-start':
            //         case 'touch-move':
            //             if (this._pageTouchStart == null) this._pageTouchStart = _.getLocation();
            //             _.getLocation(this._pageTouchDiff);
            //             this._pageTouchDiff.subtract(this._pageTouchStart);
            //             this.log('@>>>>', Math.abs(this._pageTouchDiff.x), Math.abs(this._pageTouchDiff.y));
            //             if (Math.abs(this._pageTouchDiff.x) > 10 && Math.abs(this._pageTouchDiff.y) < 10) {
            //                 this.scrollView.enabled = false;
            //             }
            //             if (this.scrollView.enabled == false) {
            //                 _.preventSwallow = true; // 可以横向滑动
            //             }
            //             break;
            //         case 'touch-end':
            //         case 'touch-cancel':
            //             this.scrollView.enabled = true;
            //             this._pageTouchStart = null;
            //             _.preventSwallow = true; // 可以横向滑动
            //             break;
            //     }
            //     if (_.preventSwallow) {
            //         this.log('可以横向滑动', this.scrollView.enabled);
            //     }
            // }),
        ];
    }

    adaptive() {
        this.viewNode.setScale(v3(Vec3.ONE).multiplyScalar(lm.getAdaptiveScale()));
        // this.contentNode.getComponent(Layout).paddingTop = 340 / lm.getAdaptiveScale();
        this.topNode.getComponent(UITransform).height *= Math.min(lm.getAdaptiveScale(), 1);
    }

    noAdsChanged() {
        this.groupNoAdsNode.active = !udm.noAds.value;
    }

    refreshItem(node: Node, info: IapProductInfo) {
        let layoutNode = find('board/Layout', node);
        for (let i = 0; i < layoutNode.children.length; i++) {
            let itemNode = layoutNode.children[i];
            if (info.provide[itemNode.name] > 0) {
                itemNode.active = true;
                let valueLabelNode = find('label', itemNode);
                if (valueLabelNode != null) {
                    if (['inf_heart_sec', 'noads_sec'].includes(itemNode.name)) {
                        let msr = MSResolve(info.provide[itemNode.name] * 1000);
                        valueLabelNode.getComponent(Label).string = MSRToString_th_m(msr);
                    } else {
                        valueLabelNode.getComponent(Label).string = `x${info.provide[itemNode.name] ?? 0}`;
                    }
                }
            } else {
                itemNode.active = false;
            }
        }
        let iapButtonItem = find('board/btn', node).getComponent(IapButtonItem);
        iapButtonItem.data.value = info;
        iapButtonItem.beforeProvideCommand.subscribe(_ => {
            gm.coinAnimatingFlags.add('iap_coin');
        }).addTo(node);
        iapButtonItem.successCommand.subscribe((provide: ProvideInfo) => {
            if (provide.coin > 0) {
                let coinSpriteNode = find('board/Layout/coin/sprite', node);
                if (coinSpriteNode != null) {
                    nc.post('fly_coins', { fromWorldPos: coinSpriteNode.worldPosition, count: provide.coin ?? 0 });
                }
            }
            gm.coinAnimatingFlags.delete('iap_coin');
        }).addTo(node);
    }

    onLoadView(): void {
        this.refresh();
    }

    clearStarter() {
        let list = this.starterContainer.children.filter(_ => _.name == 'BundleItem');
        list.forEach(_ => _.destroy());
    }

    genStarter() {
        this.clearStarter();
        let list = Object.values(DevConfig.iap).filter(_ => _.giftType == 'newbie');
        let itemCount = 0;
        for (let i = 0; i < list.length; i++) {
            let info = list[i];

            if ((udm.iapStat.value[info.productId]?.buyNum ?? 0) < (info.limited ?? Infinity)) {
                let node = instantiate(this.bundleItemPrefabNode);
                let bundleItem = node.getComponent(BundleItem);
                bundleItem.data.value = info;
                bundleItem.iapButtonItem.beforeProvideCommand.subscribe(_ => {
                    gm.coinAnimatingFlags.add('iap_coin');
                }).addTo(bundleItem.node);
                bundleItem.iapButtonItem.successCommand.subscribe((provide: ProvideInfo) => {
                    GotAwardPanel.StartProcess((panel: GotAwardPanel) => {
                        panel.data.value = provide;
                    }).subscribe(_ => {
                        if (_ == 'claim') {
                            gm.coinAnimatingFlags.delete('iap_coin');
                        }
                    });
                }).addTo(bundleItem.node);
                this.starterContainer.addChild(node);
                itemCount++;
            }
        }
        if (itemCount > 0) {
            this.groupStarterNode.active = true;
        } else {
            this.groupStarterNode.active = false;
        }
    }

    clearBundle() {
        let list = this.bundleContainer.children.filter(_ => _.name == 'BundleItem');
        list.forEach(_ => _.destroy());
    }

    genBundle() {
        this.clearBundle();
        let list = Object.values(DevConfig.iap).filter(_ => _.giftType == 'bundle');
        for (let i = 0; i < list.length; i++) {
            let info = list[i];
            let node = instantiate(this.bundleItemPrefabNode);
            let bundleItem = node.getComponent(BundleItem);
            bundleItem.data.value = info;
            bundleItem.iapButtonItem.beforeProvideCommand.subscribe(_ => {
                gm.coinAnimatingFlags.add('iap_coin');
            }).addTo(bundleItem.node);
            bundleItem.iapButtonItem.successCommand.subscribe((provide: ProvideInfo) => {
                GotAwardPanel.StartProcess((panel: GotAwardPanel) => {
                    panel.data.value = provide;
                }).subscribe(_ => {
                    if (_ == 'claim') {
                        gm.coinAnimatingFlags.delete('iap_coin');
                    }
                });
            }).addTo(bundleItem.node);
            this.bundleContainer.addChild(node);
        }
    }

    clearCoin() {
        let list = this.coinContainer.children.filter(_ => _.name == 'CoinItem');
        list.forEach(_ => _.destroy());
    }

    genCoin() {
        this.clearCoin();
        let list = Object.values(DevConfig.iap).filter(_ => _.giftType == 'coin');
        for (let i = 0; i < list.length; i++) {
            let info = list[i];
            let node = instantiate(this.coinItemPrefabNode);
            node.getComponent(CoinItem).data.value = info;
            let coinItem = node.getComponent(CoinItem);

            coinItem.iapButtonItem.beforeProvideCommand.subscribe(_ => {
                gm.coinAnimatingFlags.add('iap_coin');
            }).addTo(coinItem.node);
            coinItem.iapButtonItem.successCommand.subscribe((provide: ProvideInfo) => {
                nc.post('fly_coins', { fromWorldPos: coinItem.iconSprite.node.worldPosition, count: provide.coin ?? 0 });
                gm.coinAnimatingFlags.delete('iap_coin');
            }).addTo(coinItem.node);

            this.coinContainer.addChild(node);
        }
    }

    freeAdsButtonClicked() {
        gm.currentAdsType.value = 'AdGiveCoin';
        gm.currentAdsOpenUI.value = 'ShopPanel';
        thinking_sdk_m.requestTrack('Ads_Click', {
            AdsType: gm.currentAdsType.value,
            OpenUI: gm.currentAdsOpenUI.value,
            IsNew: udm.isNew.value
        });
        adsm.showRewardAds('free_coins').subscribe(_ => {
            if (_ == 'success') {
                thinking_sdk_m.requestTrack('Ads_Return', {
                    AdsType: gm.currentAdsType.value,
                    OpenUI: gm.currentAdsOpenUI.value,
                    IsNew: udm.isNew.value
                });
                thinking_sdk_m.requestTrack('Coins_Get', {
                    CoinNum: DevConfig.FREE_COINS,
                    Type: 'AdGiveCoin',
                    Gift_Detail: 'Other',
                    IsNew: udm.isNew.value,
                    Level_ID: udm.stageNum.value,
                });


                let coinIconNode = find('board/Layout/coin', this.freeCoinItemNode)
                nc.post('fly_coins', { fromWorldPos: coinIconNode.worldPosition, count: DevConfig.FREE_COINS });

                udm.coin.value += DevConfig.FREE_COINS;
                if (udm.freeAdsStat.value == null) udm.freeAdsStat.value = {};
                if (udm.freeAdsStat.value.freeNum) udm.freeAdsStat.value.freeNum = 0;
                udm.freeAdsStat.value.freeNum++;
                udm.freeAdsStat.value.freeAt = timem.now();
                udm.freeAdsStat.again();
                udm.save();
            }
        });
    }

    refresh() {
        this.refreshItem(this.noAds0ItemNode, DevConfig.iap.noads_0);
        this.refreshItem(this.noAds1ItemNode, DevConfig.iap.noads_1);
        this.genStarter();
        this.genBundle();
        this.genCoin();
    }

    freeAdsAvailable() {
        let freeAt = udm.freeAdsStat.value?.freeAt ?? 0;
        let freeAtNextDay = new Date(freeAt);
        freeAtNextDay.setHours(24, 0, 0, 0);
        let now = timem.now();
        if (now > freeAtNextDay.valueOf()) {
            return true;
        }
        return false;
    }

    refreshFreeAds() {
        find('board/count', this.freeCoinItemNode).getComponent(Label).string = `${DevConfig.FREE_COINS}`;
        if (this.freeAdsAvailable()) {
            this.freeAdsButton.interactable = true;
            this.freeAdsButton.getComponent(Sprite).grayscale = false;
            find('ad_icon', this.freeAdsButton.node).active = true;
            find('priceLabel', this.freeAdsButton.node).getComponent(Label).outlineColor = color().fromHEX('C15100');
        } else {
            this.freeAdsButton.interactable = false;
            this.freeAdsButton.getComponent(Sprite).grayscale = true;
            find('ad_icon', this.freeAdsButton.node).active = false;
            find('priceLabel', this.freeAdsButton.node).getComponent(Label).outlineColor = color().fromHEX('777777');
        }
    }

    tryScrollToTop() {
        if (!this._autoScrollToTop) {
            this._autoScrollToTop = true;
            this.scrollView.scrollToTop(0);
        }
    }
}
